<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useBlogStore } from '@/store/blog'
import { useAuthStore } from '@/store/auth'
import { useTypeStore } from '@/store/type'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const blogStore = useBlogStore()
const authStore = useAuthStore()
const typeStore = useTypeStore()

const blogId = route.params.id
const title = ref('')
const content = ref('')
const selectedType = ref(null)
const blogTypes = ref([])
const coverImage = ref(null)
const coverImagePreview = ref('')
const description = ref('')
const tags = ref('')
const status = ref('published')
const loading = ref(true)
const submitStatus = ref({
  submitting: false,
  success: false,
  error: false,
  message: ''
})
const editorHeight = ref('400px')
const originalBlog = ref(null)
const showTypeDialog = ref(false)
const typeLoading = ref(false)

// 富文本编辑器配置
const editorConfig = {
  placeholder: '在这里输入博客内容...',
}

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入博客标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2到100个字符之间', trigger: 'blur' }
  ],
  typeId: [
    { required: true, message: '请选择博客类型', trigger: 'change' }
  ],
  summary: [
    { required: true, message: '请输入博客摘要', trigger: 'blur' },
    { max: 500, message: '摘要长度不能超过500个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入博客内容', trigger: 'blur' }
  ]
}

// 类型表单验证规则
const typeRules = {
  typeName: [
    { required: true, message: '请输入类型名称', trigger: 'blur' },
    { min: 2, max: 20, message: '类型名称长度在2到20个字符之间', trigger: 'blur' }
  ]
}

onMounted(async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login')
    return
  }
  
  try {
    loading.value = true
    
    // 获取所有博客类型
    const typesResponse = await typeStore.getBlogTypes()
    blogTypes.value = typesResponse.data || []
    
    // 获取博客详情
    const blogResponse = await blogStore.fetchBlogById(blogId)
    originalBlog.value = blogResponse
    
    // 确保只有博客作者才能编辑
    if (originalBlog.value.userId !== authStore.user.id && !authStore.isAdmin) {
      alert('您没有权限编辑此博客')
      router.push('/user/my-blogs')
      return
    }
    
    // 填充表单数据
    title.value = originalBlog.value.title || ''
    content.value = originalBlog.value.content || ''
    selectedType.value = originalBlog.value.typeId || (blogTypes.value.length > 0 ? blogTypes.value[0].id : null)
    description.value = originalBlog.value.description || ''
    tags.value = originalBlog.value.tags || ''
    status.value = originalBlog.value.status || 'published'
    
    // 设置封面图片预览
    if (originalBlog.value.coverImage) {
      coverImagePreview.value = originalBlog.value.coverImage
    }
  } catch (error) {
    console.error('Failed to load blog data:', error)
    alert('加载博客数据失败，请重试。')
    router.push('/user/my-blogs')
  } finally {
    loading.value = false
  }
})

const handleCoverImageChange = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  if (file.size > 5 * 1024 * 1024) { // 5MB
    alert('图片大小不能超过5MB')
    return
  }
  
  coverImage.value = file
  const reader = new FileReader()
  reader.onload = (e) => {
    coverImagePreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

const removeCoverImage = () => {
  coverImage.value = null
  coverImagePreview.value = ''
}

const saveAsDraft = () => {
  status.value = 'draft'
  updateBlog()
}

const publish = () => {
  status.value = 'published'
  updateBlog()
}

const updateBlog = async () => {
  if (!title.value.trim()) {
    alert('请输入博客标题')
    return
  }
  
  if (!content.value.trim()) {
    alert('请输入博客内容')
    return
  }
  
  if (!selectedType.value) {
    alert('请选择博客分类')
    return
  }
  
  try {
    submitStatus.value.submitting = true
    
    // 构建博客数据
    const blogData = new FormData()
    blogData.append('id', blogId)
    blogData.append('title', title.value)
    blogData.append('content', content.value)
    blogData.append('typeId', selectedType.value)
    blogData.append('userId', authStore.user.id)
    blogData.append('status', status.value)
    
    if (description.value) {
      blogData.append('description', description.value)
    }
    
    if (tags.value) {
      blogData.append('tags', tags.value)
    }
    
    if (coverImage.value) {
      blogData.append('coverImage', coverImage.value)
    } else if (coverImagePreview.value) {
      // 如果没有新上传图片但有预览图，说明使用原来的封面
      blogData.append('coverImage', originalBlog.value.coverImage)
    }
    
    // 提交博客更新
    await blogStore.updateBlog(blogId, blogData)
    
    submitStatus.value.success = true
    submitStatus.value.message = '博客更新成功！'
    
    // 重定向到博客详情页
    setTimeout(() => {
      router.push(`/blogs/${blogId}`)
    }, 1500)
  } catch (error) {
    console.error('Failed to update blog:', error)
    submitStatus.value.error = true
    submitStatus.value.message = '更新博客失败，请重试。'
  } finally {
    submitStatus.value.submitting = false
  }
}

const cancelEdit = () => {
  if (confirm('确定要取消编辑吗？所有未保存的修改将丢失。')) {
    router.push('/user/my-blogs')
  }
}

const fetchBlogTypes = async () => {
  try {
    const response = await typeStore.getBlogTypes()
    if (response.code === 200) {
      blogTypes.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取博客类型失败')
  }
}

const fetchBlogDetail = async () => {
  if (!blogId) return
  
  try {
    const response = await blogStore.getBlogDetail(blogId)
    if (response.code === 200) {
      const blog = response.data
      title.value = blog.title
      content.value = blog.content
      selectedType.value = blog.typeId
      description.value = blog.description
      tags.value = blog.tags
      status.value = blog.status
      coverImagePreview.value = blog.coverImage
    }
  } catch (error) {
    ElMessage.error('获取博客详情失败')
  }
}

const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

const handleCoverUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    
    const response = await blogStore.uploadImage(formData)
    if (response.code === 200) {
      coverImage.value = response.data.imagePath
      coverImagePreview.value = response.data.imagePath
      ElMessage.success('封面图片上传成功')
    }
  } catch (error) {
    ElMessage.error('封面图片上传失败')
  }
}

const handleCreateType = async () => {
  try {
    typeLoading.value = true
    const response = await typeStore.createBlogType(typeForm.typeName)
    if (response.code === 200) {
      ElMessage.success('创建类型成功')
      showTypeDialog.value = false
      typeForm.typeName = ''
      await fetchBlogTypes()
    }
  } catch (error) {
    ElMessage.error('创建类型失败')
  } finally {
    typeLoading.value = false
  }
}

const handleSubmit = async () => {
  try {
    loading.value = true
    const blogData = {
      title: title.value,
      content: content.value,
      typeId: selectedType.value,
      userId: authStore.user.id,
      status: status.value,
      description: description.value,
      tags: tags.value,
      coverImage: coverImage.value || coverImagePreview.value
    }

    let response
    if (blogId) {
      response = await blogStore.updateBlog(blogId, blogData)
    } else {
      response = await blogStore.createBlog(blogData)
    }

    if (response.code === 200) {
      ElMessage.success(blogId ? '博客更新成功' : '博客发布成功')
      router.push('/user/my-blogs')
    }
  } catch (error) {
    ElMessage.error(blogId ? '博客更新失败' : '博客发布失败')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  router.back()
}

onMounted(() => {
  fetchBlogTypes()
  if (blogId) {
    fetchBlogDetail()
  }
})
</script>

<template>
  <div class="edit-blog">
    <div class="page-header">
      <h2 class="page-title">{{ blogId ? '编辑博客' : '创建博客' }}</h2>
    </div>
    
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
    </div>
    
    <template v-else>
      <div class="blog-form-container">
        <!-- 基本信息卡片 -->
        <div class="card blog-form-card">
          <h3 class="card-title">基本信息</h3>
          
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入博客标题" />
            </el-form-item>
            
            <el-form-item label="摘要" prop="summary">
              <textarea 
                v-model="formData.summary" 
                class="form-input textarea" 
                placeholder="请输入博客摘要（可选）"
                maxlength="500"
                rows="3"
              ></textarea>
            </el-form-item>
            
            <el-form-item label="类型" prop="typeId">
              <el-select v-model="formData.typeId" placeholder="请选择博客类型" class="type-select">
                <el-option
                  v-for="type in blogTypes"
                  :key="type.typeId"
                  :label="type.typeName"
                  :value="type.typeId"
                />
              </el-select>
              <el-button type="primary" link @click="showTypeDialog = true">
                创建新类型
              </el-button>
            </el-form-item>
            
            <el-form-item label="标签">
              <input 
                type="text" 
                v-model="formData.tags" 
                class="form-input" 
                placeholder="多个标签请用逗号分隔（可选）"
              />
            </el-form-item>
            
            <el-form-item label="状态">
              <select 
                v-model="formData.status" 
                class="form-input"
              >
                <option value="published">已发布</option>
                <option value="draft">草稿</option>
                <option value="archived">已归档</option>
              </select>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 封面图片卡片 -->
        <div class="card blog-form-card">
          <h3 class="card-title">封面图片</h3>
          
          <div class="cover-image-container">
            <div 
              v-if="coverImagePreview" 
              class="cover-image-preview"
            >
              <img :src="coverImagePreview" alt="封面预览" />
              <button 
                class="btn-remove-image" 
                title="移除图片"
                @click="removeCoverImage"
              >
                ×
              </button>
            </div>
            
            <div v-else class="cover-image-upload">
              <label for="cover-image" class="upload-label">
                <div class="upload-icon">📷</div>
                <div class="upload-text">点击上传封面图片</div>
                <div class="upload-hint">推荐尺寸: 1200 x 600，大小不超过5MB</div>
              </label>
              <input 
                type="file" 
                id="cover-image" 
                accept="image/*" 
                class="file-input" 
                @change="handleCoverImageChange"
              />
            </div>
          </div>
        </div>
        
        <!-- 博客内容卡片 -->
        <div class="card blog-form-card">
          <h3 class="card-title">博客内容</h3>
          
          <el-form-item>
            <label class="form-label required">内容编辑器</label>
            <!-- 这里使用富文本编辑器组件，根据项目实际使用的编辑器进行替换 -->
            <textarea 
              v-model="formData.content" 
              class="form-input textarea content-editor" 
              placeholder="在这里输入博客内容..."
              :style="{ height: editorHeight }"
              rows="15"
            ></textarea>
          </el-form-item>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button 
            class="btn btn-secondary" 
            @click="cancelEdit"
          >
            取消
          </button>
          
          <button 
            class="btn btn-outline" 
            @click="saveAsDraft"
            :disabled="submitStatus.submitting"
          >
            保存为草稿
          </button>
          
          <button 
            class="btn btn-primary" 
            @click="publish"
            :disabled="submitStatus.submitting"
          >
            <span v-if="submitStatus.submitting">
              <span class="spinner-small"></span> 更新中...
            </span>
            <span v-else>保存更新</span>
          </button>
        </div>
        
        <!-- 提交状态提示 -->
        <div v-if="submitStatus.success || submitStatus.error" class="submit-status">
          <div 
            class="status-message" 
            :class="{ 'success': submitStatus.success, 'error': submitStatus.error }"
          >
            {{ submitStatus.message }}
          </div>
        </div>
      </div>
    </template>

    <!-- 创建类型对话框 -->
    <el-dialog
      v-model="showTypeDialog"
      title="创建博客类型"
      width="500px"
    >
      <el-form
        ref="typeFormRef"
        :model="typeForm"
        :rules="typeRules"
        label-width="80px"
      >
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="typeForm.typeName" placeholder="请输入类型名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTypeDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreateType" :loading="typeLoading">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.edit-blog {
  padding: 0.5rem 0;
}

.page-header {
  margin-bottom: 1.5rem;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  margin: 0;
}

.blog-form-container {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.blog-form-card {
  padding: 1.5rem;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
  color: var(--primary-color);
}

.required::after {
  content: '*';
  color: var(--error-color);
  margin-left: 0.25rem;
}

.form-group {
  margin-bottom: 1.5rem;
  position: relative;
}

.form-group:last-child {
  margin-bottom: 0;
}

.char-counter {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 0.75rem;
  color: var(--text-light);
}

.textarea {
  resize: vertical;
  min-height: 100px;
}

.content-editor {
  min-height: 400px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  line-height: 1.6;
}

.cover-image-container {
  min-height: 200px;
  border: 2px dashed var(--border-color);
  border-radius: 8px;
  overflow: hidden;
}

.cover-image-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.cover-image-upload:hover {
  background-color: #f0f2f5;
}

.upload-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.upload-icon {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
}

.upload-text {
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.upload-hint {
  font-size: 0.8rem;
  color: var(--text-light);
}

.file-input {
  display: none;
}

.cover-image-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.cover-image-preview img {
  width: 100%;
  height: auto;
  display: block;
  max-height: 300px;
  object-fit: cover;
}

.btn-remove-image {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  font-size: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-remove-image:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}

.btn-outline {
  background-color: white;
  color: var(--primary-color);
  border: 1px solid var(--primary-color);
  padding: 0.625rem 1.25rem;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-outline:hover {
  background-color: #f0f4f9;
}

.submit-status {
  margin-top: 1rem;
}

.status-message {
  padding: 1rem;
  border-radius: 4px;
  text-align: center;
  font-weight: 500;
}

.status-message.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-message.error {
  background-color: #fff2f0;
  color: #f5222d;
  border: 1px solid #ffccc7;
}

.spinner-small {
  display: inline-block;
  width: 1rem;
  height: 1rem;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s linear infinite;
  margin-right: 0.5rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .btn {
    margin-bottom: 0.5rem;
  }
}

.type-select {
  width: 200px;
  margin-right: 10px;
}
</style> 